package com.example.finaldemo.ui.dashboard;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.finaldemo.GPT;
import com.example.finaldemo.MsgHelper;
import com.example.finaldemo.databinding.FragmentDashboardBinding;

public class DashboardFragment extends Fragment {

    private FragmentDashboardBinding binding;

    private boolean isThreadRunning = false;  //线程标志位，避免重复创建

    private String question="给你一段对话，请问这段对话是诈骗的可能性是多少（具体概率），为什么呢？" +
            "要求回答格式：“这段对话设计诈骗可能性为..%”+你的分析（尽量分点列出，逻辑清晰）中文" +
            "以下是对话文本：";

    private String ans = "";

    private GPT gpt = new GPT();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        DashboardViewModel dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);

        binding = FragmentDashboardBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        TextView AnswerFromGPT_TextView = binding.AnswerFromGPTTextView;
        Button SendMsg = binding.SendMsgToGPTButton;

        SendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AnswerFromGPT_TextView.setText("");
                //拼接聊天记录
                for (String str: MsgHelper.getMsgList()) {
                    question += "["+str+"]";
                }
                if (!isThreadRunning) { // 检查标志位
                    isThreadRunning = true; // 设置标志位为true
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 在新线程中执行的代码
                            ans = gpt.answer(question);
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    AnswerFromGPT_TextView.setText(ans);
                                }
                            });
                            isThreadRunning = false; // 运行结束后将标志位设为false
                        }
                    }).start();
                }
            }
        });



        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}